package com.acxy.cms.service;

import com.acxy.ants.common.enums.DataSourceType;
import com.acxy.ants.common.kit.FileKit;
import com.acxy.ants.common.kit.StrKit;
import com.acxy.ants.core.annotation.*;
import com.acxy.ants.core.exception.TipException;
import com.acxy.ants.core.kit.LogKit;
import com.acxy.ants.core.plugin.db.Db;
import com.acxy.ants.core.plugin.entity.Model;
import com.acxy.ants.core.plugin.entity.Symbol;
import com.acxy.ants.resful.bean.Page;
import com.acxy.cms.entity.Article;
import com.acxy.cms.entity.Category;
import com.alibaba.fastjson.JSON;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-06-23
 */
@Service
public class ArticleService {

    @Source(DataSourceType.DRUID)
    private Db db;

    @Autowired
    private CategoryService categoryService;


    public Page queryPage(int index, int size, Long[] catIds) {
        Article article = new Article().label("id, title, hits, _.level, _.thumb, create_time, c.cat_name as catName").orderBy("createTime", Symbol.DESC);
        article.leftJoin("left join category c on c.cat_id = _.cat_id");
        if (catIds != null && catIds.length > 0) {
            StringBuffer sb = new StringBuffer("_.cat_id in(");
            for (int i = 0; i < catIds.length; i++) {
                sb.append(catIds[i]);
                if (i != catIds.length - 1) sb.append(",");
            }
            sb.append(")");
            article.where(sb.toString());
        }
        return article.page(db, index, size);
    }

    public void save(Article article) {
        if (article.getCreateTime() == null) article.setCreateTime(new Date());
        if (article.getHits() == null) article.setHits(0);
        article.save(db);
    }

    public Article find(Long id) {
        return new Article(id).find(db);
    }

    public int update(Article article) {
        article.setUpdateTime(new Date());
        return article.update(db);
    }

    @Tx
    public int delete(Long[] ids, String rootPath) {
        if (ids == null) throw new TipException("ids 参数不能为空!");
        int res = 0;
        Article article = new Article();
        for (Long id : ids) {
            Article c = article.find(db);
            //根据ID删除文章
            c.deleteById(db, id);
            //删除图片
            String thumb = c.getThumb();
            if (StrKit.notBlank(thumb)) FileKit.delete(rootPath + thumb);
            res++;
        }
        return res;
    }
}
